# -*- coding:utf-8 -*-
import os

from browsermobproxy import Server
from selenium import webdriver
import time

WaitSecond = 5


def browser_doWait(browser):
    """
    等待一段时间
    :param browser:
    :return:
    """
    browser.implicitly_wait(WaitSecond)
    import time
    time.sleep(WaitSecond)
    pass


def getWebDriver(isProxy=False, isMain=True):
    """
    webDriver
    :param isProxy: 是否使用代理
    :param isMain: 是否从mian运行的
    :return:
    """
    driverPath = "./driver/chromedriver2.43.exe" if isMain else "./../driver/chromedriver2.43.exe"
    driverPathFirfox = "./driver/geckodriver.exe" if isMain else "./../driver/geckodriver.exe"
    prxoyPath = "./browsermob-proxy-2.1.4/bin/browsermob-proxy.bat" if isMain else "./../browsermob-proxy-2.1.4/bin/browsermob-proxy.bat"
    chrome_settings = webdriver.ChromeOptions()
    # chrome_settings.blacklist(["http://.*/.*.css.*", "http://.*/.*.jpg.*", "http://.*/.*.png.*", "http://.*/.*.gif.*"], 200)
    # chrome_settings.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
    chrome_settings.add_argument('--ignore-certificate-errors')
    chrome_settings.add_argument('--profile-directory=Default')
    chrome_settings.add_argument('--user-data-dir=C:\\Users\\dell.dell-PC\\AppData\\Local\\Google\\Chrome\\User Data')
    if (isProxy):
        proxyServer = Server(path=os.path.abspath(prxoyPath))
        proxyServer.start()
        # proxyClient = proxyServer.create_proxy()
        # 会发现打不开的情况，可能是因为代理服务的开启是异步的
        time.sleep(WaitSecond)
        chrome_settings.add_argument('--proxy-server={host}:{port}'.format(host="localhost", port=8080))#proxyClient.port
    browser = webdriver.Chrome(executable_path=driverPath, chrome_options=chrome_settings)
    browser.maximize_window()
    if (isProxy):
        return (browser, proxyServer, "")
    else:
        return browser


def logProxyContent(proxyClient):
    """
    打印出所有的请求数据
    :param proxyClient:
    :return:
    """
    for loop_record in proxyClient.har['log']['entries']:
        print(loop_record["request"]['url'])
        print(loop_record["response"]['content']["text"] if "text" in loop_record["response"]['content'] else "")


def waitInfiniti():
    """让线程一直等下去"""
    import time
    time.sleep(1000000)


def browser_changeTopWindow(browser):
    browser.switch_to.window(browser.window_handles[len(browser.window_handles) - 1])
